<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Log;
use EasyWeChat;
use Storage;

class WechatContoller extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');

        $wechat->server->setMessageHandler(function($message) {
            //$message->ToUserName;    //接收方帐号（该公众号 ID）
            // $message->FromUserName; // 用户的 openid
            //$message->CreateTime;      //消息创建时间（时间戳）
            // $message->MsgType; // 消息类型：event, text....
           // $message->MsgId         //消息 ID（64位整型）
            switch ($message->MsgType) {
                //事件处理
                case 'event':
                    switch ($message->Event) {
                        case 'subscribe': //关注事件处理
                            return $this->subscribe($message);
                            break;
                        case 'unsubscribe': //取消关注
                            return $this->unSubscribe($message);
                        case 'LOCATION': //关注事件上报地理位置
                            return '上报地理位置';
                            break;
                        default:
                            return $message->MsgType.$message->Event;
                            break;
                    }
                    break;
                case 'text':
                    return '收到文本消息 !';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        Log::info('return response.');

        return $wechat->server->serve();
    }

    /**用户关注
     * @param $message
     * @return string
     */
    public function subscribe($message)
    {
        $userService  = EasyWeChat::user(); // 用户服务
        $wxUser = $userService->get($message->FromUserName);


        $user = User::where(['openid' => $message->FromUserName])->first();
        if (!$user) {
            $user = new User();
            $user->openid = $message->FromUserName;
            $user->name = $wxUser->nickname;
            $user->subtime = $wxUser->subscribe_time;
            $user->state = 1;

            // 再判断,是否扫描的场景二维码
            if( $message->EventKey ) {
                $puid = substr( $message->EventKey , 8 );
                $row = User::find($puid);

                $user->p1 = $row['uid'];
                $user->p2 = $row['p1'];
                $user->p3 = $row['p2'];
            }

            $user->save();
        }

        if (!$user->qr_code) {
            $user->qr_code = $this->qrCode($user->uid);
            $user->save();
        }


        $msg = '欢迎您， '.$wxUser->nickname;
        return $msg;
    }

    /**取消关注
     * @param $message
     */
    public function unSubscribe($message)
    {
        $openid = $message->FromUserName;
        $user = User::where('openid', $openid)->first();

        if ($user) {
            $user->state = 0;
            $user->unsubtime = $message->CreateTime;
            $user->save();
        }
    }

    /**生成场景二维码
     * @param $uid
     */
    public function qrCode($uid)
    {
        $qrcode = EasyWeChat::qrcode(); // 二维码
        $result = $qrcode->forever($uid);

        $ticket = $result->ticket; // 或者 $result['ticket']
        $url = $qrcode->url($ticket);
        $fileName = 'qrcode/'.date('Y/m/d/').$uid.'.jpg';
        Storage::disk('admin')->put($fileName,file_get_contents($url));
        return config('admin.upload.host').$fileName;
    }
}
